<script setup lang="ts">
import { ApiDetail } from '@/api/api-manage/detail'
import axios from 'axios'
import { message } from '@/utils/message'
import { dayjs, UploadRawFile } from 'element-plus'
import { addLog } from '@/api/api-manage/log'
import { useUserStore } from '@/store/modules/user'
import { getToken } from '@/utils/auth'
import { generateApiLog } from '../../useApiLog'

const props = defineProps<{
  data: ApiDetail
}>()

const fileList = ref([] as any)
const uploadRef = ref()
const textRes = ref()
const layoutRes = ref()
const buttonLoading = ref(false)
const textLoading = ref(false)
const layoutLoading = ref(false)

/**
 * 上传文件方法
 * @param options
 */
const requestFile = async (options) => {
  if (props.data.enabledStatus != '1') {
    message('接口已停用, 请联系管理员开启', { type: 'warning' })
    return
  }
  textRes.value = null
  layoutRes.value = null
  buttonLoading.value = true
  textLoading.value = true
  layoutLoading.value = true
  const { file } = options
  const formData = new FormData()
  formData.append('file', file)
  message('正在执行OCR调用', { type: 'info' })
  let startTime = performance.now()
  const requestTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  let res = '0'
  let resCode = 500
  axios
    .post(props.data.serverProdPath + props.data.serverUri, formData)
    .then((response) => {
      if (response.data?.data) {
        let data = JSON.parse(response.data.data)
        console.log({ data })

        let s =
          `金额：${data.result.price}\n购买方：${data.result.purchaser}\n` +
          `销售方：${data.result.seller}\n购买方号码：${data.result.purchaser_id}\n` +
          `销售方号码：${data.result.seller_id}\n`
        if (data.result.table_info) {
          for(let info of data.result.table_info) {
            s += `${Object.entries(info).map(([key, value]) => `${key}：${value}`).join('\n')}\n`
          }
        }
        textRes.value = s
        message('操作成功', { type: 'success' })
        res = '1'
        resCode = 200
      } else {
        textRes.value = ''
        message('无法识别发票，请确认上传的是正确的', { type: 'warning' })
        res = '0'
        resCode = 500
      }
    })
    .catch((err) => {
      res = '0'
      resCode = 500
      message('接口存在问题无法调用', { type: 'error' })
    })
    .finally(() => {
      let endTime = performance.now()
      let duration = endTime - startTime
      const endDateTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
      let userBy = '在线体验'
      if (getToken() != null && getToken() != '') {
        userBy = useUserStore().username + userBy
      }
      const log = generateApiLog(
        props.data,
        requestTime,
        endDateTime,
        duration,
        userBy,
        res,
        resCode,
        '2'
      )
      addLog(log)
      textLoading.value = false
      buttonLoading.value = false
    })
}
</script>

<template>
  <el-upload
    ref="uploadRef"
    action="#"
    :file-list="fileList"
    :show-file-list="false"
    :http-request="requestFile"
  >
    <el-button v-loading="buttonLoading" type="primary">上传图片</el-button>
  </el-upload>
  <br />
  <el-form>
    <el-form-item v-loading="textLoading" label="证照识别结果">
      <el-input v-model="textRes" type="textarea" :rows="12" />
    </el-form-item>
  </el-form>
</template>
